package com.example.cyclops;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.MulticastSocket;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class DataUtils {
	public class PlayerControl{
		private String _name;	//just like alias
		private String _url;	//just like out
		
		private String _username;
		private String _password;
		private String _in;
		private String _hostname;
		
		public String getName(){
			return _name;
		}
		public String getUrl(){
			return _url;
		}
		public String getUsername(){
			return _username;
		}
		public String getPassword(){
			return _password;
		}
		public String getIn(){
			return _in;
		}
		public String getHostname(){
			return _hostname;
		}
		public void SetParams(String name,String username,String password){
			if(!name.equals(""))
				_name = name;
			if(!username.equals(""))
				_username = username;
			if(!password.equals(""))
				_password = password;
		}
		public JSONObject ToJson(){
			JSONObject object = new JSONObject();//创建一个总的对象，这个对象对整个json串  
			try {
				object.put("in", _in);
				object.put("hostname", _hostname);
				object.put("username", _username);
				object.put("password", _password);
				object.put("name", _name);
				object.put("out", _url);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
			}
			return object;
		}
		public PlayerControl(JSONObject jsonObj) throws JSONException{
			_name = jsonObj.getString("name"); 
			_url = jsonObj.getString("out");
			_username = jsonObj.getString("username"); 
			_password = jsonObj.getString("password");
			_hostname = jsonObj.getString("hostname"); 
			_in = jsonObj.getString("in");
		}
		public PlayerControl(String name,String url){
			_name = name;_url = url;
		}
	}
	public DataUtils(String ip,int port){
		_ip = ip;
		_port = port;
	}
	private String _ip;
	private int _port;
	//input username & password
	//return userid(>0 is correct)
	public ArrayList<PlayerControl> List(String Userid){
		ArrayList<PlayerControl> playercontrol = new ArrayList<PlayerControl>(); 
		String url = "http://" + _ip + ":" + _port + "/list?userid=" + Userid;
		String result = this.getURLResponse(url);
		if(result == ""){
			return playercontrol;
		}else{									
			JSONTokener jsonParser = new JSONTokener(result);
			try {
				JSONObject json = (JSONObject) jsonParser.nextValue();
				JSONArray jsonObjs = json.getJSONArray("list"); 
				for(int i = 0; i < jsonObjs.length() ; i++){ 
					JSONObject jsonObj = ((JSONObject)jsonObjs.opt(i));
					String _name = jsonObj.getString("name"); 
					String _url = jsonObj.getString("out");
					PlayerControl control = new PlayerControl(_name,_url);
					playercontrol.add(control);
				}
				return playercontrol;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				return playercontrol;
			}  
		}
	}
	
	public String SearchNanopi(){
		String ip = "0.0.0.0";
		try {
			MulticastSocket ms = new MulticastSocket();
			DatagramPacket dataPacket = null;  
            ms.setTimeToLive(4);  
            ms.setSoTimeout(3000);
            //将本机的IP（这里可以写动态获取的IP）地址放到数据包里，其实server端接收到数据包后也能获取到发包方的IP的  
            byte[] data = "Hi".getBytes();    
            InetAddress address = InetAddress.getByName("255.255.255.255");  
            System.out.println(address.isMulticastAddress());  
            dataPacket = new DatagramPacket(data, data.length, address,41234);  
            ms.send(dataPacket);  
            byte buf[] = new byte[1024];  
            DatagramPacket dp = new DatagramPacket(buf, 1024);  
			for(int i = 0;i < 3;i++){//try three times
				ms.receive(dp);
				if(dp.getLength() > 0){
					ip = new String(buf, 0, dp.getLength());
					ms.close();  
					break;
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
		}  
		return ip;
	}
	/*
	 [{"hostname":"192.168.10.160","username":"admin","password":"admin","in":"rtsp:\/\/\/\/192.168.10.160:554\/\/11","out":"rtmp:\/\/\/\/192.168.10.193\/\/live\/\/ch0","name":"ch0"},{"hostname":"192.168.10.128","username":"admin","password":"8888888","in":"rtsp:\/\/\/\/192.168.10.128:554\/\/tcp\/\/av0_0","out":"rtmp:\/\/\/\/192.168.10.193\/\/live\/\/ch1","name":"ch1"}]
	 * */
	public Boolean Update(String ip,ArrayList<PlayerControl> control,int userid){
		JSONArray jsonArray = new JSONArray();
		for(PlayerControl t:control)
			jsonArray.put(t.ToJson());
		String userlist = jsonArray.toString().replace("\\/", "/");
		String url = "http://" + ip + ":" + 80 + "/update?json=" + userlist;
		String ret = this.getURLResponse(url);
		if(ret.equals("")){
			return false;
		}else{
			return true;
		}
	}

	public int DeepLogin(String ip, String username,String password){
		int userid = -1;
		String url = "http://" + ip + ":" + 80 + "/login?username=" + username + "&password=" + password;
		String result = this.getURLResponse(url);
		if(result == ""){
			userid =  -1;
		}else{
			JSONTokener jsonParser = new JSONTokener(result);
			try {
				JSONObject json = (JSONObject) jsonParser.nextValue();
				userid = json.getInt("userid"); 
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
		}
		return userid;
	}
	public ArrayList<PlayerControl> DeepList(String ip){
		ArrayList<PlayerControl> playercontrol = new ArrayList<PlayerControl>(); 
		String url = "http://" + ip + ":" + 80 + "/list";
		String result = this.getURLResponse(url);
		if(result == ""){
			return playercontrol;
		}else{									
			JSONTokener jsonParser = new JSONTokener(result);
			try {
				JSONArray jsonObjs = (JSONArray) jsonParser.nextValue();
				for(int i = 0; i < jsonObjs.length() ; i++){ 
					JSONObject jsonObj = ((JSONObject)jsonObjs.opt(i));
					PlayerControl control = new PlayerControl(jsonObj);
					playercontrol.add(control);
				}
				return playercontrol;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				return playercontrol;
			}  
		}
	}
	public ArrayList<PlayerControl> Search(String ip){
		ArrayList<PlayerControl> playercontrol = new ArrayList<PlayerControl>(); 
		String url = "http://" + ip + ":" + 80 + "/search";
		String result = this.getURLResponse(url);
		if(result == ""){
			return playercontrol;
		}else{									
			JSONTokener jsonParser = new JSONTokener(result);
			try {
				JSONArray jsonObjs = (JSONArray) jsonParser.nextValue();
				for(int i = 0; i < jsonObjs.length() ; i++){ 
					JSONObject jsonObj = ((JSONObject)jsonObjs.opt(i));
					PlayerControl control = new PlayerControl(jsonObj);
					playercontrol.add(control);
				}
				return playercontrol;
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				return playercontrol;
			}  
		}
	}
	
	public int Login(String username,String password){
		int userid = -1;
		String url = "http://" + _ip + ":" + _port + "/login?username=" + username + "&password=" + password;
		String result = this.getURLResponse(url);
		if(result == ""){
			userid =  -1;
		}else{
			JSONTokener jsonParser = new JSONTokener(result);
			try {
				JSONObject json = (JSONObject) jsonParser.nextValue();
				userid = json.getInt("userid"); 
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}  
		}
		return userid;
	}
	/** 
     * 从指定URL获取图片 
     * @param url 
     * @return 
     */  
    private Bitmap getImageBitmap(String url){  
        URL imgUrl = null;  
        Bitmap bitmap = null;  
        try {  
            imgUrl = new URL(url);  
            HttpURLConnection conn = (HttpURLConnection)imgUrl.openConnection();  
            conn.setDoInput(true);  
            conn.setConnectTimeout(3000);
            conn.connect();  
            InputStream is = conn.getInputStream();  
            bitmap = BitmapFactory.decodeStream(is);  
            is.close();  
        } catch (MalformedURLException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }catch(IOException e){  
            e.printStackTrace();  
        }  
        return bitmap;  
    }  
	private String getURLResponse(String urlString){
        HttpURLConnection conn = null; //连接对象  
        InputStream is = null;  
        String resultData = "";  
        try {  
            URL url = new URL(urlString); //URL对象  
            conn = (HttpURLConnection)url.openConnection(); //使用URL打开一个链接  
            conn.setDoInput(true); //允许输入流，即允许下载  
            //conn.setDoOutput(true); //允许输出流，即允许上传  
            conn.setUseCaches(false); //不使用缓冲  
            conn.setRequestMethod("GET"); //使用get请求  
            conn.setConnectTimeout(3000);
            conn.connect();
            is = conn.getInputStream();   //获取输入流，此时才真正建立链接  
            InputStreamReader isr = new InputStreamReader(is);  
            BufferedReader bufferReader = new BufferedReader(isr);  
            String inputLine  = "";  
            while((inputLine = bufferReader.readLine()) != null){  
                resultData += inputLine + "\n";  
            }  
  
        } catch (MalformedURLException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }catch (IOException e) {  
            // TODO Auto-generated catch block  
            e.printStackTrace();  
        }finally{  
            if(is != null){  
                try {  
                    is.close();  
                } catch (IOException e) {  
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                }  
            }  
            if(conn != null){  
                conn.disconnect();  
            }  
        }  
  
        return resultData;  
	}
}
